/**
 * 系统管理--用户管理的单例对象
 */
var MgrUser = {
    id: "managerTable",//表格id
    seItem: null,		//选中的条目
    seItems: null,		//多选中的条目
    table: null,
    layerIndex: -1,
    deptid:0,
    currentid:0,      //当前弄得id
    settings:null,    //新增ztree属性设置
    //isSingle: 1,     //单选或多选
    radioIsture: true,
    checkboxIsture: false,
    currentPageNum:1,
};

/**
 * 初始化表格的列
 */
MgrUser.initColumn = function () {
    var columns = [
        // {field: 'selectItem', radio: MgrUser.radioIsture},
        {field: 'checkbox', checkbox: true},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle', width: '120'},
        {title: '工号', field: 'jobnum', visible: false, align: 'center', valign: 'middle', sortable: true},
        {title: '账号', field: 'account', align: 'center', valign: 'middle', sortable: true, width: '120'},
        {title: '姓名', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '100'},
        {title: '性别', field: 'sexName', align: 'center', valign: 'middle', sortable: true, width: '70'},
        {title: '生日', field: 'birthday', align: 'center', valign: 'middle', sortable: true, width: '105'},
        {title: '角色', field: 'roleName', align: 'center', valign: 'middle', sortable: true},
        {title: '部门', field: 'deptName', align: 'center', valign: 'middle', sortable: true},
        {title: '职位', field: 'position', align: 'center', valign: 'middle', sortable: true},
        {title: '等级', field: 'grade', align: 'center', valign: 'middle', sortable: true},
        {title: '邮箱', field: 'email', align: 'center', valign: 'middle', sortable: true},
        {title: '电话', field: 'phone', align: 'center', valign: 'middle', sortable: true, width: '100'},
        {title: '创建时间', field: 'createtime', align: 'center', valign: 'middle', sortable: true, width: '150'},
        {title: '状态', field: 'statusName', align: 'center', valign: 'middle', sortable: true, width: '70',cellStyle:function(value,row,index){
        	　　　if (value=='冻结'){
        	　　　　　　return {css:{"color":"red"}}
        	　　　}else{
        	　　　　　　return {css:{"color":"green"}}
        	　　　}
        	}},
        {title: '入职时间', field: 'entrytime', visible: false, align: 'center', valign: 'middle', sortable: true, width: '150'},
        {title: '离职时间', field: 'dimissiontime', visible: false, align: 'center', valign: 'middle', sortable: true, width: '150'},
        {title: '操作', field: 'operate', align: 'center', valign: 'middle', width: '50', events: operateEvents, formatter: operateFormatter, width: '70'}];
    return columns;
};

/**
 * 检查是否选中
 */
MgrUser.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0 || selected.length > 1) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        MgrUser.seItem = selected[0];
        return true;
    }
};

/**
 * 检查是否有多个选中
 */
MgrUser.checks = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的记录！");
        return false;
    } else {
        MgrUser.seItems = selected;
        return true;
    }
};

/**
 * 点击添加管理员
 */
MgrUser.openAddMgr = function () {
    var index = layer.open({
        type: 2,
        title: '添加管理员',
        area: ['1200px', '580px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/mgr/user_add'
    });
    this.layerIndex = index;
};

/**
 * 点击修改按钮时
 * @param userId 管理员id
 */
MgrUser.openChangeUser = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '编辑管理员',
            area: ['800px', '490px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/mgr/user_edit/' + this.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 点击角色分配
 * @param
 */
MgrUser.roleAssign = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '角色分配',
            area: ['300px', '400px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/mgr/role_assign/' + this.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 删除用户
 */
MgrUser.delMgrUser = function () {
		if (this.checks()) {
	        var operations = function(){
	        	var users = MgrUser.seItems;
	        	var userIds = new Array();
	        	for(var i = 0; i <= users.length-1; i++){
	        		userIds[i] = users[i].id;
	        	}
	        	$.ajax({
	        		type:"GET",
	        		url:Feng.ctxPath + "/mgr/deletes",
	        		data:{"userIds":userIds},
	        		traditional:true,
	        		success:function(data){
	        			Feng.success("删除成功!");
	        			MgrUser.table.refresh();
	        		},
	        		error:function (data) {
		                Feng.error("删除失败!!");
	    	            },
	        	});
	        };

	        Feng.confirm("是否删除选中的用户?",operations);
	}

};
//*******************dxl***********************************
MgrUser.isCheckbox = function(){
	//变为多选，初始化表格
	this.radioIsture = false;
	this.checkboxIsture = true;
	$('#managerTable').bootstrapTable('destroy');
	var defaultColunms = MgrUser.initColumn();
    var table = new BSTable("managerTable", "/mgr/list", defaultColunms, 717);
    table.setPaginationType("client");
    MgrUser.table = table.init();
    
    //初始化table后，跳到当前查看的页
//    MgrUser.currentPageNum = $('#managerTable').bootstrapTable('getOptions').pageNumber;
//    alert(MgrUser.currentPageNum);
//    $('#managerTable').bootstrapTable('selectPage',currentPageNum);
    //实现‘多选’-‘取消多选按钮的实现’
    $('#userAdd').attr('disabled', 'true');
	//$('#userAdd').removeClass().addClass('btn btn-default')
	$('#userEdit').attr('disabled', 'true');
	$('#managerTable').bootstrapTable('hideColumn','selectItem');
	$('#managerTable').bootstrapTable('showColumn','checkbox');
	$('#userNoCheckbox').css('display','');
	$('#userIsCheckbox').css('display','none');
	//this.isSingle = 2;
}
MgrUser.noCheckbox = function(){
	//取消多选，初始化表格
	this.radioIsture = true;
	this.checkboxIsture = false;
	$('#managerTable').bootstrapTable('destroy');
	var defaultColunms = MgrUser.initColumn();
    var table = new BSTable("managerTable", "/mgr/list", defaultColunms, 717);
    table.setPaginationType("client");
    MgrUser.table = table.init();
    
  //初始化table后，跳到当前查看的页
    currentPageNum = $('#managerTable').bootstrapTable('getOptions').pageNumber;
    $('#managerTable').bootstrapTable('selectPage',currentPageNum);
  //实现‘多选’-‘取消多选按钮的实现’
	$('#userAdd').removeAttr('disabled');
	//$('#userAdd').removeClass().addClass('btn btn-default')
	$('#userEdit').removeAttr('disabled');
	$('#managerTable').bootstrapTable('hideColumn','checkbox');
	$('#managerTable').bootstrapTable('showColumn','selectItem');
	$('#userIsCheckbox').css('display','');
	$('#userNoCheckbox').css('display','none');
	//this.isSingle = 1;
}
/**
 * 冻结用户账户
 * @param userId
 */
MgrUser.freezeAccount = function () {
    if (this.checks()) {
        var operations = function(){
            var users = MgrUser.seItems;
            var userIds = new Array();
            for(var i = 0; i <= users.length-1; i++){
                userIds[i] = users[i].id;
            }
            $.ajax({
                type:"GET",
                url:Feng.ctxPath + "/mgr/freezes",
                data:{"userIds":userIds},
                traditional:true,
                success:function(data){
                    Feng.success("冻结成功!");
                    MgrUser.table.refresh();
                },
                error:function (data) {
                    Feng.error("冻结失败!!");
                },
            });
        };

        Feng.confirm("是否冻结选中的用户?",operations);
    }

};

/**
 * 解除冻结用户账户
 * @param userId
 */
MgrUser.unfreeze = function () {
    if (this.checks()) {
        var operations = function(){
            var users = MgrUser.seItems;
            var userIds = new Array();
            for(var i = 0; i <= users.length-1; i++){
                userIds[i] = users[i].id;
            }
            $.ajax({
                type:"GET",
                url:Feng.ctxPath + "/mgr/unfreezes",
                data:{"userIds":userIds},
                traditional:true,
                success:function(data){
                    Feng.success("解除冻结成功!");
                    MgrUser.table.refresh();
                },
                error:function (data) {
                    Feng.error("解除冻结失败!!");
                },
            });
        };

        Feng.confirm("是否解除冻结选中的用户?",operations);
    }
}

/**
 * 重置密码
 */
MgrUser.resetPwd = function () {
    if (this.check()) {
        var userId = this.seItem.id;
        parent.layer.confirm('是否重置密码为111111？', {
            btn: ['确定', '取消'],
            shade: false //不显示遮罩
        }, function () {
            var ajax = new $ax(Feng.ctxPath + "/mgr/reset", function (data) {
                Feng.success("重置密码成功!");
            }, function (data) {
                Feng.error("重置密码失败!");
            });
            ajax.set("userId", userId);
            ajax.start();
        });
    }
};

MgrUser.resetSearch = function () {
    $("#name").val("");
    $("#beginTime").val("");
    $("#endTime").val("");

    MgrUser.search();
}

MgrUser.search = function () {
    var queryData = {};

    queryData['deptid'] = MgrUser.deptid;
    queryData['name'] = $("#name").val();
    queryData['beginTime'] = $("#beginTime").val();
    queryData['endTime'] = $("#endTime").val();

    MgrUser.table.refresh({query: queryData});
}

MgrUser.onClickDept = function (e, treeId, treeNode) {
    MgrUser.deptid = treeNode.id;
    MgrUser.search();
};

$(function () {
    var defaultColunms = MgrUser.initColumn();
    var table = new BSTable("managerTable", "/mgr/list", defaultColunms, 717);
    table.setPaginationType("client");
    MgrUser.table = table.init();
    var ztree = new $ZTree("deptTree", "/dept/tree");
    ztree.bindOnClick(MgrUser.onClickDept);
    ztree.init({view:{
    	addHoverDom: addHoverDom,
    	removeHoverDom: removeHoverDom
    }});
});


//*************************
function addHoverDom(treeId, treeNode) {
	var aObj = $("#" + treeNode.tId + "_a");
	if ($("#diyBtn_"+treeNode.id).length>0) return;
	var editStr = "<span id='diyBtn_space_" +treeNode.id+ "' > </span>"
		+ "<span id='diyBtn_" + treeNode.id
		+ "'onfocus='this.blur();'>" +
				"<span title='本部门' id='deptUsers' style='font-family:Glyphicons Halflings;color:green;font-size:13px;padding-left:10px;' class='glyphicon glyphicon-user'>" +
				"</span>";
	aObj.append(editStr);
	var deptUsersbn = $("#diyBtn_"+treeNode.id+" #deptUsers");
	if (deptUsersbn) {
		deptUsersbn.on('click',function(e) {
			e.stopPropagation()
			MgrUser.selectDeptUsers(treeId, treeNode)
		})
	}
};
function removeHoverDom(treeId, treeNode) {
	$("#diyBtn_"+treeNode.id).unbind().remove();
	$("#diyBtn_space_" +treeNode.id).unbind().remove();
};
MgrUser.selectDeptUsers = function (treeId, treeNode) {
	            var ajax = new $ax(Feng.ctxPath + "/mgr/selectDeptUsers",function (data) {
	            	MgrUser.table.load(data||[])
	            }, function (data) {
	            	MgrUser.table.load([])
	            	Feng.error('查询本部门人员失败！')
	            })
	            ajax.set("deptid", treeNode.id);
	            ajax.start();
	            
};
//************************

//////////////dxl
/**
 * 点击查看详情
 */
MgrUser.detailMgr = function () {
    var index = layer.open({
        type: 2,
        title: '详情',
        area: ['1200px', '580px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/mgr/user_detail/' + this.currentid
    });
    this.layerIndex = index;			
};

function operateFormatter(value, row, index) {
   return [
   '<button type="button" class="RoleOfdelete btn btn-primary  btn-sm" style="margin-right:15px;">详情</button>'//,

   //'<button type="button" class="RoleOfedit btn btn-primary  btn-sm" style="margin-right:15px;">修改</button>'
   ].join('');
   }

window.operateEvents = {
        'click .RoleOfdelete': function (e, value, row, index) {
        	MgrUser.currentid = row.id;
            //alert(JSON.stringify(row)); 
            MgrUser.detailMgr()
            //console.log(row)
     }//,
//        'click .RoleOfedit': function (e, value, row, index) {
//            $("#editModal").modal('show');
//
//        }
};

////////////////